package com.nwpu.coursesupport.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.RoleType;
import com.nwpu.coursesupport.realm.CustomizedToken;
import com.nwpu.coursesupport.service.imple.AssistantService;
import com.nwpu.coursesupport.service.imple.StudentService;
import com.nwpu.coursesupport.service.imple.TeacherService;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.LoginParam;
import com.nwpu.coursesupport.service.param.RegisterParam;

@Controller	
@RequestMapping(value="/user")
public class UserController extends AbstractController{
	
    private static Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
    private StudentService studentService;
	@Autowired
    private TeacherService teacherService;
	@Autowired
    private AssistantService assistantService;
	
    @RequestMapping(value="/register",method=RequestMethod.POST)
    @ResponseBody
	public JSONResult register(@RequestBody RegisterParam user) {
		JSONResult rst = new JSONResult();
		rst.fail();
		if (user.getType() == RoleType.STUDENT) {
			rst = studentService.create(user);
		} else if (user.getType() == RoleType.ASSISTANT) {
			rst = assistantService.create(user);
		} else if (user.getType() == RoleType.TEACHER) {
			rst = teacherService.create(user);
		}
		return rst;
	}
    
    @RequestMapping(value="/detail",method=RequestMethod.GET)
    public String detail(HttpServletRequest request){
    	RoleType roleType=(RoleType) getSession().getAttribute("roleType");
    	int id =(int) getSession().getAttribute("id");
    	JSONResult rst=new JSONResult();
    	IDParam p=new IDParam();
    	p.setId(id);
    	switch(roleType){
    	case STUDENT:
    		rst=this.studentService.detail(p);
    		break;
    	case ASSISTANT:
    		rst=this.assistantService.detail(p);
    		break;
    	case TEACHER:
    		rst=this.teacherService.detail(p);
    		break;
    		default:
    			rst.fail("参数错误");
    	}
    	request.setAttribute("data", this.parseData(rst));
    	return "/common/personalInfo";
    }
    
    
    @RequestMapping(value="/update",method=RequestMethod.GET)
    public String toUpdate(HttpServletRequest request){
    	RoleType roleType=(RoleType) getSession().getAttribute("roleType");
    	int id =(int) getSession().getAttribute("id");
    	JSONResult rst=new JSONResult();
    	IDParam p=new IDParam();
    	p.setId(id);
    	switch(roleType){
    	case STUDENT:
    		rst=this.studentService.detail(p);
    		break;
    	case ASSISTANT:
    		rst=this.assistantService.detail(p);
    		break;
    	case TEACHER:
    		rst=this.teacherService.detail(p);
    		break;
    		default:
    			rst.fail("参数错误");
    	}
    	request.setAttribute("data", this.parseData(rst));
    	return "/common/personalInfo";
    }
    
    @RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult update(@RequestParam("data")String data){
    	RoleType roleType=(RoleType) getSession().getAttribute("roleType");
    	JSONResult rst=new JSONResult();
    	switch(roleType){
    	case STUDENT:
    		rst=invokeService("student","update",data);
    		break;
    	case ASSISTANT:
    		rst=invokeService("assistant","update",data);
    		break;
    	case TEACHER:
    		rst=invokeService("teacher","update",data);
    		break;
    	default:
    			rst.fail("参数错误");
    	}
    	RegisterParam user=(RegisterParam) getSession().getAttribute("user") ;
    	if(user !=null){
    		getSession().setAttribute("name",user.getName());
    	}
		return rst;
	}
	
    @RequestMapping(value="/changeAvatar",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult changeAvatar(@RequestParam("data")String data){
    	RoleType roleType=(RoleType) getSession().getAttribute("roleType");
    	JSONResult rst=new JSONResult();
    	switch(roleType){
    	case STUDENT:
    		rst=invokeService("student","updateAvatar",data);
    		break;
    	case ASSISTANT:
    		rst=invokeService("assistant","updateAvatar",data);
    		break;
    	case TEACHER:
    		rst=invokeService("teacher","updateAvatar",data);
    		break;
    	default:
    			rst.fail("参数错误");
    	}
		return rst;
	}
    
    
	@RequestMapping("/login")
	@ResponseBody
	public JSONResult login(@RequestBody LoginParam user){
		JSONResult rst=new JSONResult();
		rst.fail();		
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated() == false) {//该用户未登录
			if(user.getType()==null){
				user.setType(RoleType.STUDENT);
			}
			
			CustomizedToken token = new CustomizedToken(user.getUserCode(),user.getPassword(), user.getType());
			try {
				currentUser.login(token);// 将用户名和
				logger.debug("登录成功");
				rst.success();
				rst.addData("userCode",user.getUserCode());
				rst.addData("roleType", user.getType());
				System.out.println(getSession().getAttribute("username"));
			} catch (AuthenticationException e) {
				logger.error("登录失败");
				rst.fail("用户名或密码错误");
			}
			return rst;
		}else{//该用户已登录 直接返回成功
			rst.addData("userCode", getSession().getAttribute("username"));
			rst.addData("roleType", getSession().getAttribute("roleType"));
			return rst.success();
		}
		
	}

	@RequestMapping("/welcome")
	public String welcome(){
		return "success";
	}
	
	@RequestMapping("/logout")
	public String logout(){
		SecurityUtils.getSubject().logout(); 
		return "redirect:/common/login.jsp";
	}
	

}
